using Microsoft.AspNetCore.Authorization;

namespace PiggyBankCashFlowApi.Middleware;

public class AuthenticationLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<AuthenticationLoggingMiddleware> _logger;

    public AuthenticationLoggingMiddleware(RequestDelegate next, ILogger<AuthenticationLoggingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        // 记录所有请求的认证信息
        var endpoint = context.GetEndpoint();
        var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
        
        _logger.LogInformation("Request: {Method} {Path}", context.Request.Method, context.Request.Path);
        _logger.LogInformation("Authorization Header: {Header}", authHeader);
        _logger.LogInformation("Endpoint: {Endpoint}", endpoint?.DisplayName);
        
        if (endpoint != null)
        {
            var authorizeData = endpoint.Metadata.GetOrderedMetadata<IAuthorizeData>();
            _logger.LogInformation("Authorize Data: {Count}", authorizeData.Count);
            foreach (var auth in authorizeData)
            {
                _logger.LogInformation(" - Policy: {Policy}, Roles: {Roles}, Schemes: {Schemes}", 
                    auth.Policy, auth.Roles, auth.AuthenticationSchemes);
            }
        }

        await _next(context);
        
        _logger.LogInformation("Response: {StatusCode} for {Path}", 
            context.Response.StatusCode, context.Request.Path);
    }
}